package com.wusuowei.generator.controller;

import com.wusuowei.common.annotation.Log;
import com.wusuowei.common.constant.BusinessTypeEnum;
import com.wusuowei.common.utils.R;
import com.wusuowei.generator.common.core.text.Convert;
import com.wusuowei.generator.model.po.GenTable;
import com.wusuowei.generator.model.vo.PageGenTableVo;
import com.wusuowei.generator.service.IGenTableColumnService;
import com.wusuowei.generator.service.IGenTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/gen")
public class GenController
{
    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list")
    public R dataList(PageGenTableVo queryParams)
    {
        Map<String, Object> map = new HashMap<>();
        List<GenTable> list = genTableService.selectDbTableList(queryParams);
        map.put("total",list.size());
        map.put("records",list);
        return R.ok().setData(map);
    }

    /**
     * 查询代码生成列表
     */
    @GetMapping("/list")
    public R genList(GenTable genTable)
    {
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        Map<String, Object> map = new HashMap<>();
        map.put("total",list.size());
        map.put("records",list);
        return R.ok().setData(map);
    }

    /**
     * 导入表结构（保存）
     */
    //@PreAuthorize("@ss.hasPermi('tool:gen:import')")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.IMPORT)
    @PostMapping("/importTable")
    public R importTableSave(String tables)
    {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return R.ok();
    }

    /**
     * 预览代码
     */
    //@PreAuthorize("@ss.hasPermi('tool:gen:preview')")
    @GetMapping("/preview/{tableId}")
    public R preview(@PathVariable("tableId") Long tableId) throws IOException
    {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok().setData(dataMap);
    }
}